var md5 = require('blueimp-md5')
var moment = require('moment')
var Base64 = require('js-base64').Base64
var request = require('request')

/*生成指定的随机数*/

function randomCode(length) {
    var chars = ['0','1','2','3','4','5','6','7','8','9'];
    var result = " ";
    for(var i = 0; i<length;i++){
        var index = Math.ceil(Math.random()*9);
        result += chars[index]
    }
     return result
}

exports.randomCode = randomCode;

/*向指定号码发送指定验证码*/
function sendCode(phone, code, callback) {
    var ACCOUNT_SID = '8aaf07086bdeb007016be421653b046c';
    var AUTH_TOKEN = '7bea9654982c46e395aceb4cf65f8aca';
    var Rest_URL = 'https://app.cloopen.com:8883';
    var APP_ID = '8aaf07086bdeb007016be421658f0472';

    var sigParameter = '';
    var time = moment().format('YYYYMMDDHHmmss');
    sigParameter = md5(ACCOUNT_SID + AUTH_TOKEN + time)
    var url = Rest_URL + '/2013-12-16/Accounts/' + ACCOUNT_SID + '/SMS/TemplateSMS?sig=' + sigParameter;

    /*准备请求*/
    var body = {
        to: phone,
        appId: APP_ID,
        templateId: '1',
        "datas": [code, "1"]
    }

    var authorization = ACCOUNT_SID + ':' + time;
    authorization = Base64.encode(authorization);
    var headers = {
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset = utf-8',
        'Content-Length': JSON.stringify(body).length + '',
        'Authorization': authorization
    }

    /*4.发送请求*/

    request({
        method:'POST',
        url:url,
        headers:headers,
        body:body,
        json:true
    },function (error, response, body) {
        console.log(error,response,body);
        callback(body.statusCode==='000000')
    })
}

exports.sendCode = sendCode;